package com.github.tommas.admintpl.security;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.github.tommas.admintpl.common.CommonResult;
import com.github.tommas.admintpl.common.CommonResultCode;
import org.apache.shiro.web.filter.authc.UserFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;

public class UserAuthorizationFilter extends UserFilter {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserAuthorizationFilter.class);

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletResponse resp = (HttpServletResponse) response;
        resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

        Exception ex = (Exception) request.getAttribute(JWTAwareSubjectFactory.TOKEN_EXCEPTION_ATTR);
        if (ex == null) {
            return false;
        }

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("JWT Verification exception", ex);
        }

        CommonResult result;
        if (ex instanceof TokenExpiredException) {
            result = new CommonResult(CommonResultCode.TOKEN_EXPIRED.getCode(), CommonResultCode.TOKEN_EXPIRED.getMessage(), null);
        } else {
            result = CommonResult.failed("Invalid token", null);
        }

        OutputStream stream = resp.getOutputStream();
        JSON.writeJSONString(stream, result);
        stream.flush();

        return false;
    }
}
